package com.findyou.headline.controller;

import com.findyou.headline.common.Result;
import com.findyou.headline.common.ResultCodeEnum;
import com.findyou.headline.pojo.NewsUser;
import com.findyou.headline.service.NewsUserService;
import com.findyou.headline.service.impl.NewsUserServiceImpl;
import com.findyou.headline.util.JwtHelper;
import com.findyou.headline.util.MD5Util;
import com.findyou.headline.util.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user/*")
public class NewsUserController extends BaseController{
    private NewsUserService userService = new NewsUserServiceImpl();
    /**
     * 处理登录表单提交的业务接口的实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收用户名和密码
        NewsUser paramUser = WebUtil.readJson(req, NewsUser.class);
        //调用服务层
       NewsUser loginUser = userService.findByUsername(paramUser.getUsername()); // 根据用户名去查询
        Result result = null;
        if(null == loginUser) {
            result = Result.build(null, ResultCodeEnum.USERNAME_ERROR); // 返回 用户名出现问题
        } else {
            boolean equals = MD5Util.encrypt(paramUser.getUserPwd()).equalsIgnoreCase(loginUser.getUserPwd()); // 密码忽略大小写
            if(equals) {
                Integer uid = loginUser.getUid();
                String token = JwtHelper.createToken(uid.longValue());
                Map data = new HashMap();
                data.put("token", token); // 以键值对的形式 响应给前端
                result = Result.ok(data);
            } else {
                result = Result.build(null, ResultCodeEnum.PASSWORD_ERROR); // 返回给前端密码错误
            }
        }
        //向客户端响应登录验证信息
        WebUtil.writeJson(resp, result);
    }

    /**
     * 根据token口令获得用户信息的接口实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void getUserInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求中的token
        String token = req.getHeader("token");
        Result result = Result.build(null,ResultCodeEnum.NOTLOGIN);
        if(null != token && !"".equals(token)) {
            boolean expiration = JwtHelper.isExpiration(token); // 没过期返回的是false
            if(!expiration) {
                Integer userId = JwtHelper.getUserId(token).intValue();
                NewsUser newsUser = userService.findByUid(userId);
                if(null != newsUser) {
                    Map data = new HashMap();
                    newsUser.setUserPwd("");
                    data.put("loginUser", newsUser); //这是和前端的保持一致
                    result = Result.ok(data);
                }
            }else {

            }
        }
        //校验token
             // 通过校验  查询用户信息放入 Result
             // 未通过校验   响应Result 设置为504
        WebUtil.writeJson(resp, result); // 响应为前端
    }


    /**
     *校验用户名时候被占用的校验
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void checkUserName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result =  Result.ok(null); // 默认是存的200 也就是可以的
        // 获取前端传过来的用户名
        String name = req.getParameter("user");
        NewsUser newUser = userService.findByUsername(name);
        //根据用户名查询用户信息  找到了 返回505 找不到返回200 也就是可以去注册了
        if(null != newUser) { // 说明用户名已经存在了
            result = Result.build(null, ResultCodeEnum.USERNAME_USED);
        }
        WebUtil.writeJson(resp, result);//转换切JSON 响应给前端
    }

    /**
     *完成注册的业务接口
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接收JSON信息
        NewsUser registUser = WebUtil.readJson(req, NewsUser.class);
        // 调用服务层将用户信息存入数据
        Integer rows = userService.registUser(registUser); // 影响数据库的行数
        //根据存入时候成功的结果返回 处理响应值
        Result result = Result.ok(null);
        if(rows == 0) {
            result = Result.build(null, ResultCodeEnum.USERNAME_USED);
        }
        WebUtil.writeJson(resp, result);

    }

    /**
     * 用户客户端 自己校验是否失去登录状态的接口
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void checkLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String token = req.getHeader("token");
        Result result = Result.build(null, ResultCodeEnum.NOTLOGIN); // 先默认是过期 或者是不行的 也就是登不上了
        if(null != token) {
            boolean expiration = JwtHelper.isExpiration(token); // 过期没有 true 表示过期了
            if(!expiration) {
                result = Result.ok(null);
            }
        }
        WebUtil.writeJson(resp, result);
    }
}
